package com.gf.pokemon.controller;

import javax.annotation.Resource;
import javax.servlet.http.HttpSession;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.gf.pokemon.constants.PokeConstants;
import com.gf.pokemon.dto.LoginUser;
import com.gf.pokemon.platform.exception.PokeErrorCode;
import com.gf.pokemon.platform.exception.PokeException;
import com.gf.pokemon.platform.result.PokeResult;
import com.gf.pokemon.service.AdminUserService;

@Controller
@RequestMapping("/admin")
public class LoginController {
	
	private final String SUCCESS = "ok";
	
	@Resource
	private AdminUserService adminUserService;
	
	@RequestMapping("/show")
	public ModelAndView show() throws Exception{
		return new ModelAndView("login");
	}

	@RequestMapping("/login")
	@ResponseBody
	public String login(String username,String password,HttpSession httpSession) throws Exception{
		if(username==null){
			throw new PokeException(PokeErrorCode.INVALID_PARAM,"用户名为空");
		}
		if(password==null){
			throw new PokeException(PokeErrorCode.INVALID_PARAM,"密码为空");
		}		
		LoginUser loginUser = adminUserService.getLoginUser(username);
		if(loginUser==null){
			throw new PokeException(PokeErrorCode.INVALID_PARAM,"用户不存在");
		}
		if(!password.equals(loginUser.getPassword())){
			throw new PokeException(PokeErrorCode.INVALID_PARAM,"密码错误");
		}
		httpSession.setAttribute(PokeConstants.SESSION_USER, loginUser);
		return PokeResult.getPokeResultSuccess(SUCCESS);
	}
	
	@RequestMapping("/logout")
	public ModelAndView logout(HttpSession httpSession) throws Exception{
		httpSession.setAttribute(PokeConstants.SESSION_USER, null);
		return new ModelAndView("login");
	}
	
	public AdminUserService getAdminUserService() {
		return adminUserService;
	}

	public void setAdminUserService(AdminUserService adminUserService) {
		this.adminUserService = adminUserService;
	}

}
